const mongoose = require("mongoose")
const db = 'mongodb://localhost:27017/douban-test'
const glob = require("glob")
const {resolve} = require("path")
mongoose.Promise = global.Promise

exports.initSchemas = ()=>{
    glob.sync(resolve(__dirname, "./schema", "**/*.js")).forEach(require)
}

exports.connect = () => {

    let maxConnectTimes = 0

    return new Promise((resolve, reject)=>{
        if (process.env.NODE_ENV !== 'production'){
            mongoose.set('debug', true)
        }
        mongoose.connect(db,{useNewUrlParser:true})

        mongoose.connection.on('disconnected', ()=>{
           
            maxConnectTimes++
            if (maxConnectTimes < 5){
                mongoose.connect(db)
            } else {
                throw new Error("数据库连接错误")
            }
            
        })
    
        mongoose.connection.on('error', err=>{
            maxConnectTimes++
            if (maxConnectTimes < 5){
                mongoose.connect(db)
            } else {
                throw new Error("数据库连接错误")
            }
        })
        mongoose.connection.once('open', ()=>{
            // const Dog = mongoose.model('Dog', {name: String})
            // const doga = new Dog({name: '阿尔法'})
            // doga.save().then(()=>{
            //     console.log('save success')
            // })
            resolve()
            console.log("mongodb connected success")
        })
    })

}

/*
MongoDB
    document
        键值对，一行记录
    collection
        多个文档，表
    database
        多个集合，数据库
Mongoose
    schema
        数据模式，数据类型，数据长度，表字段的定义
    model
        模型，具备某张表操作能力的函数集合
    entity
        model所创建的数据实体，某条数据，集成方法可以修改
*/ 